#region using

using System;
using System.Web;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core;
using System.Net.Mail;
using System.Threading;
using System.Data;
using System.Text.RegularExpressions;

#endregion

/// <summary>
/// Chris Blankenship
/// www.dscoduc.com
/// 
/// Description: Increases your readership and RSS subscription rate by simply sending a short 'thank you' relishing type message to users when they first comment on your weblog.
///  
/// Inspired by Justin Shattuck - http://www.justinshattuck.com/comment-relish/
/// 
/// </summary>
[Extension("Sends an e-mail to the user after they have submitted a comment.", "1.0", "<a target=\"_blank\" href=\"http://www.dscoduc.com\">DSCODUC</a>")]
public class CommentRelish
{
    static protected ExtensionSettings _settings = null;
    static protected ExtensionSettings _history = null;

    /// <summary>
	/// Hooks up an event handler to the Post.CommentAdded event.
	/// </summary>
	public CommentRelish()
	{
        Post.CommentAdded += new EventHandler<EventArgs>(Post_CommentAdded);

        ExtensionSettings settings = new ExtensionSettings("CommentRelish");
        settings.AddParameter("messageSubject", "Response Subject", 200);
        settings.AddParameter("messageBody", "Response Body (html)", 500);

        // Load default values
        settings.AddValue("messageSubject", "Thank you for your comment on my blog " + BlogSettings.Instance.Name);
        settings.AddValue("messageBody", "<h3>Thank you for submitting a comment</h3><p>I really appreciate you taking the time to let me know your thoughts.</p>");

        settings.Help = "<br />Increase readership and RSS subscription rate by simply sending a short 'thank you' relishing type message to users when they first comment on your weblog.<br />";

        settings.IsScalar = true;
        ExtensionManager.ImportSettings(settings);
        _settings = ExtensionManager.GetSettings("CommentRelish");

    }

    private void Post_CommentAdded(object sender, EventArgs e)
	{
        Post post = (Post)((Comment)sender).Parent;

        // No sense sending an email to yourself
        if (post != null && !Thread.CurrentPrincipal.Identity.IsAuthenticated)
		{
            // Skip Trackback and Pingback posts
            Comment comment = post.Comments[post.Comments.Count - 1];
            if (comment.Email == "trackback" || comment.Email == "pingback")
            {
                return;
            }

            // Load history table
            _history = ExtensionManager.GetSettings("CommentRelishHistory");

            // Check if we should send this to the same person more than once
            if (ShouldSend(comment.Email))
            {
                // Prepare the message
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(BlogSettings.Instance.Email, BlogSettings.Instance.AuthorName);
                mail.To.Add(HttpUtility.HtmlDecode(comment.Email));

                mail.Subject = _settings.GetSingleValue("messageSubject");
                mail.Body = "<div style=\"font: 12px verdana, arial\">";
                mail.Body += _settings.GetSingleValue("messageBody");
                mail.Body += "<br />" + string.Format("<strong>{0}</strong>: <a href=\"{1}\">{2}</a><br /><br />", Resources.labels.post, post.PermaLink + "#id_" + comment.Id, post.Title);
                mail.Body += "<br />" + BlogSettings.Instance.AuthorName;
                mail.Body += "</div>";

                // Send the message
                Utils.SendMailMessageAsync(mail);
                
                // Update the sent email table
                LogEmailSent(comment.Email, HttpUtility.HtmlDecode(comment.Website.OriginalString));
            }
		}    
    }

    // Checks a table of past users to see if we have previously sent them an email
    // If the user has already been sent an email and the sendFirstOnly flag is false then we send again
    private bool ShouldSend(string emailAddress)
    {
        RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline;
        Regex REGEX = new Regex(emailAddress, options);

        // Check if the user has already been sent an email
        DataTable table = _history.GetDataTable();
        foreach (DataRow row in table.Rows)
        {
            
            if (REGEX.IsMatch((string)row["EmailAddress"]))
            {
                // Looks like we have already sent this person an email... 
                // Let's not bother them with another!
                return false;
            }
        }
        // If we got here then there wasn't a previous record for the users email address            
        // Lets send them an email!
        return true;
    }

    // Updates table to reflect that we have sent the user an email
    private void LogEmailSent(string emailAddress, string userWebsite)
    {
        _history.AddValue("EmailAddress", emailAddress);
        _history.AddValue("lastSentDate", DateTime.Now.AddHours(BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd HH\\:mm"));
        _history.AddValue("Website", userWebsite);
        _history.AddValue("IPAddress", HttpContext.Current.Request.UserHostAddress);

        ExtensionManager.SaveSettings("CommentRelishHistory", _history);
    }
}
